<template>
  <view style="background: #ffffff">
    <canvas
      v-if="!tempFilePath"
      :canvas-id="CanvasID"
      :style="{ width: canvasW + 'px', height: canvasH + 'px' }"
    ></canvas>
    <image
      v-else
      lazy-load
      :src="tempFilePath"
      mode="widthFix"
      class="is-response"
    ></image>
  </view>
</template>

<script>
var _this;
export default {
  name: "cc-poster",
  props: {
    CanvasID: {
      //CanvasID 等同于 canvas-id
      Type: String,
      default: "PosterCanvas",
    },
    imgSrc: {
      //展示图
      Type: String,
      default: "",
    },
    QrSrc: {
      //二维码
      Type: String,
      default: "",
    },
    TitleColor: {
      //标题颜色
      Type: String,
      default: "#333333",
    },
    LineType: {
      //标题显示行数 大于两行是否省略	（注超出2行显示会导致画布布局絮乱）
      Type: [String, Boolean],
      default: true,
    },
    OriginalColor: {
      //默认颜色（如原价与扫描二维码颜色）
      Type: String,
      default: "#b8b8b8",
    },
    Width: {
      //画布宽度  (高度根据图片比例计算 单位upx)
      Type: String,
      default: 750,
    },
    CanvasBg: {
      //canvas画布背景色
      Type: String,
      default: "#ffffff",
    },
    Referrer: {
      //推荐人信息
      Type: String,
      default: "",
    },
    ViewDetails: {
      //描述提示文字
      Type: String,
      default: "",
    },
    poptitle: {
      //推荐人信息
      Type: String,
      default: "邀请好友加入本维美",
    },
    popDetails: {
      //描述提示文字
      Type: String,
      default: "我的团队邀请你加入",
    },
    avatar: {
      Type: String,
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      tempFilePath: "",
      canvasW: 0,
      canvasH: 0,
      canvasImgSrc: "",
      ctx: null,
    };
  },
  methods: {
    async OnCanvas() {
      // this.loading = true;
      _this.ctx = uni.createCanvasContext(_this.CanvasID, this);
      const C_W = uni.upx2px(_this.Width), //canvas宽度
        C_P = uni.upx2px(30), //canvas Paddng 间距
        C_Q = uni.upx2px(130); //二维码或太阳码宽高
      let _strlineW = 0; //文本宽度

      let _imgInfo = await _this.getImageInfo({
        imgSrc: _this.imgSrc,
      }); //广告图
      console.log(
        "图片信息0：",
        JSON.stringify(""),
        _this.imgSrc,
        _imgInfo.path
      );

      let _QrCode = await _this.getImageInfo({
        imgSrc: _this.QrSrc,
      }); //二维码或太阳码

      console.log("图片信息1：", JSON.stringify(""));

      let r = [_imgInfo.width, _imgInfo.height];
      let q = [_QrCode.width, _QrCode.height];

      let imgW = C_W - C_P * 2;
      if (r[0] != imgW) {
        r[1] = Math.floor((imgW / r[0]) * r[1]);
        r[0] = imgW;
      }
      if (q[0] != C_Q) {
        q[1] = Math.floor((C_Q / q[0]) * q[1]);
        q[0] = C_Q;
      }
      _this.canvasW = C_W;
      _this.canvasH = r[1] + q[1] + 128;
      _this.ctx.setFillStyle(_this.CanvasBg); //canvas背景颜色
      _this.ctx.fillRect(0, 0, C_W, _this.canvasH); //canvas画布大小
      //添加图片展示
      _this.ctx.drawImage(_imgInfo.path, C_P, 88, r[0], r[1]);
      //添加图片展示 end
      //设置文本
      _this.ctx.setFontSize(uni.upx2px(35)); //设置标题字体大小
      _this.ctx.setFillStyle(_this.TitleColor); //设置标题文本颜色

      const setText = (context, fs, color, x, y, c, bold) => {
        context.setFillStyle(color);
        context.setTextAlign("center");
        if (bold) {
          context.font = "normal bold 20px Arial,PingFang SC";
        } else {
          context.font = "normal 20px Arial,PingFang SC";
        }
        context.setFontSize(fs);
        context.fillText(c, x, y);
        context.restore();
      };
      setText(_this.ctx, 19, "#333", r[0] / 2, 40, _this.poptitle, "bold");
      setText(_this.ctx, 15, "#999", r[1] / 2, 70, _this.popDetails);

      // let _strLastIndex = 0; //每次开始截取的字符串的索引
      // let _strHeight = r[1] + C_P * 2 + 10; //绘制字体距离canvas顶部的初始高度
      let _num = 1;
      // for (let i = 0; i < _this.Title.length; i++) {
      // 	_strlineW += _this.ctx.measureText(_this.Title[i]).width;
      // 	if (_strlineW > r[0]) {
      // 		if (_num == 2 && _this.LineType) {
      // 			//文字换行数量大于二进行省略号处理
      // 			_this.ctx.fillText(_this.Title.substring(_strLastIndex, i - 8) + '...', C_P, _strHeight);
      // 			_strlineW = 0;
      // 			_strLastIndex = i;
      // 			_num++;
      // 			break;
      // 		} else {
      // 			_this.ctx.fillText(_this.Title.substring(_strLastIndex, i), C_P, _strHeight);
      // 			_strlineW = 0;
      // 			_strHeight += 20;
      // 			_strLastIndex = i;
      // 			_num++;
      // 		}
      // 	} else if (i == _this.Title.length - 1) {
      // 		_this.ctx.fillText(_this.Title.substring(_strLastIndex, i + 1), C_P, _strHeight);
      // 		_strlineW = 0;
      // 	}
      // }
      //设置文本 end
      //设置价格
      // _strlineW = C_P;
      // _strHeight += uni.upx2px(60);
      // if (_num == 1) {
      // 	_strHeight += 20; //单行标题时占位符
      // }
      let _strHeight = r[1] + C_P * 2 + 78;
      // _this.ctx.strokeStyle = _this.OriginalColor;
      // _this.ctx.moveTo(_strlineW, _strHeight - uni.upx2px(10)); //起点
      // _this.ctx.lineTo(_strlineW + _this.ctx.measureText(_this.OriginalTxt).width, _strHeight - uni.upx2px(
      // 	10)); //终点
      // _this.ctx.stroke();
      //设置价格 end

      //添加二维码
      _strHeight += uni.upx2px(20);
      _this.ctx.drawImage(
        _QrCode.path,
        r[0] - q[0] + C_P,
        _strHeight,
        q[0],
        q[1]
      );
      //添加二维码 end

      //添加推荐人与描述
      _this.ctx.setFillStyle(_this.TitleColor);
      _this.ctx.setFontSize(uni.upx2px(32));
      _this.ctx.fillText(_this.Referrer, C_P + 105, _strHeight + q[1] / 2 - 15);
      _this.ctx.setFillStyle(_this.OriginalColor);
      _this.ctx.setFontSize(uni.upx2px(26));
      _this.ctx.fillText(
        _this.ViewDetails,
        C_P + 105,
        _strHeight + q[1] / 2 + 15
      );
      //添加推荐人与描述 end

      _this.ctx.beginPath();
      let avatar_width = 60; //头像宽度
      let avatar_height = 60; //头像高度
      let avatar_x = 15; //头像的x坐标
      let avatar_y = _strHeight; //头像的y坐标
      let radius = 30; //头像的圆角弧度
      // 绘制圆角头像
      this.setRadius(
        _this.ctx,
        avatar_width,
        avatar_height,
        avatar_x,
        avatar_y,
        radius,
        _this.avatar
      );
      var gradient = _this.ctx.createLinearGradient(
        200,
        200,
        C_W,
        _this.canvasH
      );
      gradient.addColorStop(0, "red");
      gradient.addColorStop(1, "blue");

      // 将渐变设置为填充样式
      _this.ctx.fillStyle = gradient;

      // 绘制一个具有渐变背景的矩形
      _this.ctx.fillRect(50, 50, 150, 100);
      //延迟后渲染至canvas上
      setTimeout(function () {
        _this.ctx.draw(true, (ret) => {
          uni.hideLoading();
          _this.getNewImage();
        });
      }, 600);
    },
    setRadius(
      ctx,
      avatar_width,
      avatar_height,
      avatar_x,
      avatar_y,
      radius,
      QrCode
    ) {
      /**
       * 绘制圆角
       */
      ctx.arc(
        avatar_x + radius,
        avatar_y + radius,
        radius,
        Math.PI,
        (Math.PI * 3) / 2
      );
      ctx.lineTo(avatar_width - radius + avatar_x, avatar_y);
      ctx.arc(
        avatar_width - radius + avatar_x,
        radius + avatar_y,
        radius,
        (Math.PI * 3) / 2,
        Math.PI * 2
      );
      ctx.lineTo(avatar_width + avatar_x, avatar_height + avatar_y - radius);
      ctx.arc(
        avatar_width - radius + avatar_x,
        avatar_height - radius + avatar_y,
        radius,
        0,
        (Math.PI * 1) / 2
      );
      ctx.lineTo(radius + avatar_x, avatar_height + avatar_y);
      ctx.arc(
        radius + avatar_x,
        avatar_height - radius + avatar_y,
        radius,
        (Math.PI * 1) / 2,
        Math.PI
      );
      // 开始填充
      ctx.strokeStyle = "#fff";
      ctx.fill(); //保证图片无bug填充
      ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内

      ctx.drawImage(QrCode, avatar_x, avatar_y, avatar_width, avatar_height);
      ctx.closePath();
      ctx.restore();
    },
    async getImageInfo({ imgSrc }) {
      return new Promise((resolve, errs) => {
        uni.getImageInfo({
          src: imgSrc,
          success: function (image) {
            resolve(image);
          },
          fail(err) {
            errs(err);

            uni.showToast({
              title: "海报生成失败",
              mask: false,
              duration: 2000,
              icon: "none",
            });
            uni.hideLoading();
          },
        });
      });
    },
    getNewImage() {
      uni.canvasToTempFilePath(
        {
          canvasId: _this.CanvasID,
          quality: 1,
          complete: (res) => {
            _this.tempFilePath = res.tempFilePath;
            _this.$emit("success", res);
            _this.loading = false;
            uni.hideLoading();
          },
        },
        this
      );
    },
  },
  mounted() {
    _this = this;
    this.OnCanvas();
  },
};
</script>

<style lang="scss" scoped>
.btn {
  width: 334rpx;
  height: 100rpx;
  flex-shrink: 0;
  border-radius: 50rpx;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  margin-top: 80rpx;

  .btn-test {
    color: #ff4254;
    font-family: "PingFang SC";
    font-size: 28rpx;
    font-style: normal;
    font-weight: 500;
    display: flex;
    justify-content: center;
  }

  .btn-img {
    width: 36rpx;
    height: 36rpx;
  }
}
</style>
